package com.lxyk.yygh.oss.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.net.MediaType;
import com.lxyk.yygh.common.result.Result;
import com.lxyk.yygh.oss.service.FileService;
import com.lxyk.yygh.oss.utils.ConstantOssPropertiesUtils;
import com.lxyk.yygh.oss.utils.HttpUtil;
import com.lxyk.yygh.oss.vo.UserAuthVO;
import com.lxyk.yygh.oss.vo.OCRData;
import com.lxyk.yygh.oss.vo.medicalRecord.MedicalRecord;
import com.lxyk.yygh.oss.vo.medicalRecord.MedicalRecordVO;
import okhttp3.OkHttpClient;
import org.apache.tomcat.util.codec.binary.Base64;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {
    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();
    private static final String APIKEY="20YqrAhPUiRSFORPI3HNdWId";
    private static final String SECRETKEY="4L2Fex23tuw2cIftHunfR06zp0GYCGbb";
    private static final String GRANTYPE="client_credentials";

    //上传文件到阿里云OSS
    @Override
    public UserAuthVO upload(MultipartFile file) {
        // Endpoint以广州为例，其它Region请按实际情况填写。
        String ednpoint = ConstantOssPropertiesUtils.EDNPOINT;
        String accessKeyId = ConstantOssPropertiesUtils.ACCESS_KEY_ID;
        String secrect = ConstantOssPropertiesUtils.SECRECT;
        String bucket = ConstantOssPropertiesUtils.BUCKET;

        //创建OssClient实例
        OSS ossClient = new OSSClientBuilder().build(ednpoint, accessKeyId, secrect);

        try {
            //上传文件流。
            InputStream inputStream = file.getInputStream();
            String fileName = file.getOriginalFilename();

            //生成随机唯一值，使用uuid，添加到文件名称里面
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            fileName=uuid+fileName;
            //按照当前日期，创建文件夹，上传到创建文件夹里面
            //  2021/02/02/01.jpg
            String timeUrl = new DateTime().toString("yyyy/MM/dd");
            fileName= timeUrl + "/" + fileName;

            //调用方法实现上传
            ossClient.putObject(bucket,fileName,inputStream);
            //关闭ossClient
            ossClient.shutdown();
            //上传之后文件路径
            //https://yygh-yyghwqbgz.oss-cn-guangzhou.aliyuncs.com/2023/07/15/39c9fe14539e4653a72f0e740f3ac322头像.jpg
            String url = "https://"+bucket+"."+ednpoint+"/"+fileName;

            //获取身份证信息
            String data = upload_tow(file);
            ObjectMapper objectMapper = new ObjectMapper();
            OCRData ocrData = objectMapper.readValue(data, OCRData.class);

            // 可以使用 ocrData 对象来访问解析后的数据
            UserAuthVO userAuth = new UserAuthVO();
            if(StringUtils.isEmpty(ocrData)||ocrData.getWords_result().get公民身份号码()==null){
                userAuth.setCertificatesUrl(url);
                return userAuth;
            }
            userAuth.setName(ocrData.getWords_result().get姓名().getWords());
            userAuth.setCertificatesNo(ocrData.getWords_result().get公民身份号码().getWords());
            userAuth.setCertificatesType(10);
            userAuth.setGender(ocrData.getWords_result().get性别().getWords().equals("男")?1:2);
            userAuth.setCertificatesUrl(url);

            //返回路径
            return userAuth;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public Result uploadrecord(MultipartFile file) {
        //file 文件空校验
        if(file.isEmpty()){
            return null;
        }
        String imageBase64=null;
        try {
            byte[] imageBytes=file.getBytes();
            imageBase64= Base64.encodeBase64String(imageBytes);
        }catch (IOException e){
            e.printStackTrace();
        }
        //请求开始
        String url = "https://aip.baidubce.com/rest/2.0/ocr/v1/medical_record";
        try {
            // 本地文件路径

            String imgParam = URLEncoder.encode(imageBase64, "UTF-8");
            String param = "image=" + imgParam;

            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
            String accessToken = "24.e64f3be8c97c0955f667fd144a8bd5b4.2592000.1716530275.282335-63305125";

            String result = HttpUtil.post(url, accessToken, param);
            JSONObject jsonObject = JSONObject.parseObject(result);

            // 可以使用 ocrData 对象来访问解析后的数据
            return Result.ok(jsonObject);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String upload_tow(MultipartFile file){
        //file 文件空校验
        if(file.isEmpty()){
            return "图片上传失败";
        }
        String imageBase64=null;
        try {
            byte[] imageBytes=file.getBytes();
            imageBase64= Base64.encodeBase64String(imageBytes);
        }catch (IOException e){
            return  "未识别";
        }
        //请求开始
        String url="https://aip.baidubce.com/rest/2.0/ocr/v1/idcard";//请求路径固定
        try {
            // 本地文件路径
//            String filePath = "C:\\Users\\Administrator\\Desktop\\身份证识别陈朋涛.png";
//            byte[] imgData = FileUtil.readFileByBytes(filePath);
//            String imgStr = Base64Util.encode(imgData);
            String imgParam = URLEncoder.encode(imageBase64, "UTF-8");

            String param = "id_card_side=" + "front" + "&image=" + imgParam;

            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间30天， 客户端可自行缓存，过期后重新获取。
            String accessToken = "24.6889be73a31c8fbccec7bdcc764569d8.2592000.1716537333.282335-63334530";

            String result = HttpUtil.post(url, accessToken, param);
            return result;
        } catch (Exception e) {
            return  "未识别";
        }
    }
}
